import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/view/login/attestation_company_request.dart';
import 'package:provider/provider.dart';

class CompanyType extends StatefulWidget {
  @override
  _CompanyTypeState createState() => _CompanyTypeState();
}

class _CompanyTypeState extends State<CompanyType> {
  File _image;
  final picker = ImagePicker();
  String fileName;
  FormData formData;
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    // TODO 苹果端是否可以显示图片，并上传
    var pickedFile = await picker.getImage(
        source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);
    fileName = pickedFile.path.split('/').last;

    setState(() {
      _image = File(pickedFile.path);
    });
    formData = FormData.fromMap({
      "name": _NameController.text,
      "business_license": await MultipartFile.fromFile(
        pickedFile.path,
        filename: fileName,
      ),
    });
  }

//  Future<void> retrieveLostData() async {
//    final LostData response = await picker.getLostData();
//    if (response == null) {
//      return;
//    }
//    if (response.file != null) {
//      setState(() {
//        if (response.type == RetrieveType.video) {
//          return;
//        } else {
//
//          _image = File(response.file.path);
//        }
//      });
//    } else {
//      return;
//    }
//  }

  FocusNode _focusNodeName = new FocusNode();
  TextEditingController _NameController = new TextEditingController();
  var _isShowClear = false; //是否显示输入框尾部的
  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodeName.hasFocus) {
      print("用户名框获取焦点");
      // 取消密码框的焦点状态
    }
  }

  @override
  void initState() {
    _focusNodeName.addListener(_focusNodeListener);
    _NameController.addListener(() {
      print(_NameController.text);
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_NameController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _focusNodeName.removeListener(_focusNodeListener);
    _NameController.dispose();

    super.dispose();
  }

  //验证输入内容
  String validateVode(value) {
    if (value.isEmpty) {
      return '验证码不能为空';
    }
  }

  var errorname;

  @override
  Widget build(BuildContext context) {
    return ListenableProvider<AttestationCompanyRequest>(
      create: (_) {
        AttestationCompanyRequest model = AttestationCompanyRequest();
        return model;
      },
      child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text(
              "企业认证",
              style: TextStyle(
                color: Colors.black,
                fontSize: 32.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
            backgroundColor: Colors.white,
            elevation: 0,
            leading: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Icon(
                Icons.arrow_back_ios,
                color: Color(0xFF000000),
              ),
            ),
          ),
          body: ListView(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(50.w, 50.h, 50.w, 0),
                child: Container(
                    child: Form(
                      key: _formKey,
                      child: TextFormField(
                        style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                        focusNode: _focusNodeName,
                        controller: _NameController,
                        decoration: InputDecoration(
                            errorText: errorname,
                            errorStyle: TextStyle(
                                color: Color(0xFFFE0600), fontSize: 20.sp),
                            hintText: "企业简称",
                            prefixIcon: Builder(
                                builder: (context) => FlatButton(
                                  child: Text(
                                    "公司名称",
                                    style: TextStyle(
                                        fontSize: 26.sp,
                                        color: Color(0xFF000000)),
                                  ),
                                  onPressed: null,
                                )),
                            suffixIcon: (_isShowClear)
                                ? IconButton(
                              icon: Icon(
                                Icons.cancel,
                                size: 27.sp,
                              ),
                              onPressed: () {
                                _NameController.clear();
                              },
                            )
                                : Text("")),
                        validator: validateVode,
                      ),
                    )),
              ),
              Padding(
                padding: EdgeInsets.fromLTRB(50.w, 50.h, 50.w, 0),
                child: Container(
                    alignment: Alignment.center,
                    child: Text(
                      "上传企业执照",
                      style: TextStyle(
                        fontSize: 28.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    )),
              ),
              Padding(
                padding: EdgeInsets.fromLTRB(50.w, 50.h, 50.w, 0),
                child: Container(
                  decoration: BoxDecoration(
                    border: new Border.all(width: 1, color: Colors.red),
                  ),
                  width: 560.w,
                  height: 315.w,
                  child: GestureDetector(
                    child: _image == null
                        ? Image.asset("images/business_license@2x.png")
                        : Image.file(
                      _image,
                      fit: BoxFit.contain,
                    ),
                    onTap: _pickImage,
                  ),
                ),
              ),
              Padding(
                  padding: EdgeInsets.fromLTRB(80.w, 150.h, 80.w, 0),
                  child: Container(
                      height: 100.h,
                      color: Colors.lightBlue,
                      child: Builder(
                        builder: (context) => FlatButton(
                          child: Text(
                            "提交审核",
                            style: TextStyle(color: Colors.white),
                          ),
                          onPressed: () {
                            if ((_formKey.currentState).validate()) {
                              context
                                  .read<AttestationCompanyRequest>()
                                  .business(formData, onSuccess: () {
                                Navigator.pop(context);
                                Navigator.of(context)
                                    .pushNamed(Routes.attestation_finish);

                              }, onFail: (error) {
                                errorname = error;
                              });
                            }
                          },
                        ),
                      )))
            ],
          )),
    );
  }

  _pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
          height: 250.h,
          child: Column(
            children: <Widget>[
              _item("拍照", true),
              _item("从相册选择", false),
            ],
          ),
        ));
  }

  _item(String title, bool isTakePhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isTakePhoto ? Icons.camera : Icons.photo_library),
        title: Text(
          title,
          style: TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
        ),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }
}
